'''

http://www.lrts.me/ajax/playlist/2/265/1

chapter_num = 章节：<span>157</span> <br />

name = <input type="hidden" value="(.*?)" name="player-r-name"/>


url  = <input type="hidden" value="(.*?)" name="source" />

'''
import requests

import re

import queue

import threading

from spider import *

class LanRenTingShu(Spider):

    def get_info(self):
        #print(regexs)
        super().get_info(
            chapter_num = '章节：<span>(.*?)</span> <br />',
            name = '<input type="hidden" value="(.*?)" name="player-r-name"/>',
            url  = '<input type="hidden" value="(.*?)" name="source" />',
                 )
        #print(self.info_dict)

        self.chapter_num = int(self.info_dict['chapter_num'][0])

        self.info = zip(self.info_dict['name'],self.info_dict['url'])

    
    def save_file(self):

        while True:

            print(threading.active_count())
            #print(threading.enumerate())
            try:
                info = next(self.info)
            except StopIteration:
                print('{}退出 '.format(threading.current_thread().name))
                break
                

            thread_count = threading.active_count()

            if thread_count<7:
                
                self.life_thread()


            #print(info[0])

            name = info[0].replace(';','').replace('&#x',r'\u').encode().decode('unicode_escape',errors = 'ignore')
            url = info[1]
            
            r = requests.get(url,headers = self.headers)
            content = r.content
            with open(name+'.mp3','wb') as f:
                f.write(content)

            print(name+'  下载完成')

    def life_thread(self):
        
        t = threading.Thread(target = self.save_file)

        t.start()
        

        

def fan_ye(id1,id2):

    url = 'http://www.lrts.me/ajax/playlist/{}/{}/1'.format(id1,id2)

    x = Spider(url)
    count = int(x.get_info(count = '章节：<span>(.*?)</span> <br />')['count'][0])

    val = count//10 + 1

    for i in range(val):

        url = 'http://www.lrts.me/ajax/playlist/{}/{}/{}'.format(id1,id2,val*10+1)
        x = LanRenTingShu(url)
        x.get_info()
        x.my_thread(5)
        
if __name__ == '__main__':
    
    x = LanRenTingShu(url = 'http://www.lrts.me/ajax/playlist/2/5181/1',
                      charset = 'utf-8')
    x.get_info()
    x.life_thread()



































    
